const axios = require("axios");
const { github, OAUTH_URL } = require("../config");

const { github_token_url, client_id, client_secret, redirect_uri } = github;

module.exports = (server) => {
  server.use(async (ctx, next) => {
    //  点击了去注册
    if (ctx.path === "/auth") {
      const code = ctx.query.code;
      if (!code) {
        ctx.body = "code not exist";
        return;
      }
      // 去github请求token接口请求用户的token
      const result = await axios({
        method: "POST",
        url: github_token_url,
        data: {
          code,
          client_id,
          redirect_uri,
          client_secret,
        },
        headers: {
          Accept: "application/json",
        },
      });
      // 如果请求的结果成功，且没有返回错误消息(有时候错误了，但是还是会返回200)
      if (result.status === 200 && result.data && !result.data.error) {
        // 将token存储到session
        ctx.session.githubAuth = result.data;

        const { access_token, token_type } = result.data;

        const userInfoResp = await axios({
          method: "GET",
          url: "https://gitee.com/api/v5/user",
          headers: {
            Authorization: `${token_type} ${access_token}`,
          },
        });
        // console.log(userInfoResp.data);
        ctx.session.userInfo = userInfoResp.data;

        ctx.redirect("/");
        ctx.redirect((ctx.session && ctx.session.urlBeforeOAuth) || "/");
        ctx.session.urlBeforeOAuth = "";
      } else {
        ctx.body = "request token failed !";
      }
    } else {
      await next();
    }
  });

  server.use(async (ctx, next) => {
    const path = ctx.path;
    const method = ctx.method;
    if (path === "/logout" && method === "POST") {
      ctx.session = null;
      ctx.body = "logout success";
    } else {
      await next();
    }
  });

  // 去登录前记录登录前的路由
  server.use(async (ctx, next) => {
    const path = ctx.path;
    const method = ctx.method;
    if (path === "/prepare-auth" && method === "GET") {
      // ctx.session = null;
      // ctx.body = "logout success";
      const { url } = ctx.query;
      ctx.session.urlBeforeOAuth = url;
      // ctx.body = "ready";
      ctx.redirect(OAUTH_URL);
    } else {
      await next();
    }
  });
};
